//
//  AppDelegate.swift
//  SwiftTest
//
//  Created by 陈旺 on 2022/1/19.
//

import UIKit
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
            UNUserNotificationCenter.current().getNotificationSettings { (settings) in
                switch settings.authorizationStatus {
                case .authorized:
                    DispatchQueue.main.async {
                        UIApplication.shared.registerForRemoteNotifications()
                        print(UIApplication.shared.isRegisteredForRemoteNotifications)
                    }
                case .notDetermined:
                    UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
                        if granted {
                            DispatchQueue.main.async {
                                UIApplication.shared.registerForRemoteNotifications()
                                print(UIApplication.shared.isRegisteredForRemoteNotifications)
                            }
                        }
                    }
                default:
                    break
                }
            }
        } else {
            // Fallback on earlier versions
        }
        self.window = UIWindow.init(frame: UIScreen.main.bounds)
        self.window?.rootViewController = ViewController()
        self.window?.makeKeyAndVisible()
        return true
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        if #available(iOS 13.0, *) {
            var deviceTokenString: String = ""
            let bytes = [UInt8](deviceToken)
            for item in bytes {
                deviceTokenString += String(format:"%02x", item&0x000000FF)
            }
            print("注册deviceToken:\(deviceTokenString)")
        }else {
            let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
            print("注册deviceToken:\(deviceTokenString)")
        }
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("注册推送失败....")
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.sound, .badge])
    }
        
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        UserDefaults.standard.set("2", forKey: "key1")
        UserDefaults.standard.synchronize()
        completionHandler()
    }
    
    // 专门用来处理"content-available"推送
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if UIApplication.shared.applicationState == .background {
            UserDefaults.standard.set("3", forKey: "key2")
            UserDefaults.standard.synchronize()
        }else if UIApplication.shared.applicationState == .active {
            UserDefaults.standard.set("4", forKey: "key2")
            UserDefaults.standard.synchronize()
        }
        completionHandler(.newData)
    }
        
    func applicationWillTerminate(_ application: UIApplication) {
        UserDefaults.standard.removeObject(forKey: "key1")
        UserDefaults.standard.removeObject(forKey: "key2")
        UserDefaults.standard.synchronize()
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        
    }
    
}

